<?php
/* 
 * PHP file that gets and parses the Squid log file from the Squid server.
 * Returns an array of strings.
 *
 * Author: Baron Gerarld S. Manzano
 *
 */

class SQParser {
	protected $rawstrings = array();
	protected $datalines = array();
	protected $sundays = array();
	protected $size = NULL;
	
	/*
	 * Instantiates SQParser that calls the different functions below to parse the contents of a Squid log file.
	 */
	public function __construct(){
		set_time_limit(0);
		$this->rawstrings = $this->readLog();
		$this->size = count($this->rawstrings);
		
		for($c=0;$c<$this->size;$c++){
			$this->datalines[] = $this->parseLine($this->rawstrings[$c], $c);
		}
	}
	
	/*
	 * Opens the log file and puts the lines in an array.
	 * Originally, it performs a UNIX SSH command to get the log file from the ITC server.
	 * If it fails, it gets a dummy log file stored locally instead.
	 * Feel free to edit the UNIX command and the file name as needed.
	 */
	private function readLog(){ 
		exec("ssh squidtest@172.16.11.1 'cat /var/log/squid/access.log'", $output, $ret);
		
		if($ret != 0){
			$data = file_get_contents("access.log");
			$token = strtok($data,"\n\r");
			
			while($token != false){
				$output[] = $token;
				$token = strtok("\n\r");
			}
		}
		return $output;
	}

	/*
	 * This function parses the text array retrieved from the log file.
	 * It also stores the relevant information in the database as well.
	 * Feel free to change the MySQL log-in information as needed.
	 * Output array, data[], is of this format:
	 *		IP Address
	 *		Date
	 *		Time
	 *		Webpage Visited
	 *		Content Type
	 */
	private function parseLine($str, $num){
		$token = strtok($str," ");
		
		while($token !== false){
			$store[] = $token;
			$token = strtok(" ");
		}
		$size = count($store);
		
		$con = mysql_connect("localhost","sqadmin","squid");
		if (!$con){
			die("Could not connect: " . mysql_error());
			return;
		}
		
		$data[] = $store[2];
		$data[] = date("M/d/y", $store[0]);
		$data[] = date("H:i:s", $store[0]);
		$data[] = $store[6];
		$data[] = $store[9];
		
		mysql_select_db("squidler", $con);
		$info = mysql_query("SELECT * FROM logdata WHERE timestamp='$store[0]' AND ipadd='$store[2]' AND webpageid='$num'");
		
		if(mysql_num_rows($info) == 0){
			$info2 = mysql_query("INSERT INTO logdata (timestamp, ipadd, webpageid, ctype, webpageclass) VALUES('$store[0]', '$store[2]', '$num', '$store[9]', NULL)") or die(mysql_error());
		}
		
		mysql_close($con);
		
		return $data;
	}
	
	/*
	 * Getter function for a specific logfile line.
	 */
	public function getDataLine($index){
		return $this->datalines[$index];
	}
	
	/*
	 * Getter function for the logfile array size.
	 */
	public function getSize(){
		return $this->size;
	}

}

?>
